package admin

import (
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/admin"

	"github.com/gin-gonic/gin"
)

func RefreshToken(c *gin.Context) {

	requestData := struct {
		RefreshToken string `json:"refreshToken"`
	}{}
	c.ShouldBindJSON(&requestData)

	var adminTokenStruct admin.AdminTokenStruct
	exists, err := model.GetModelDataFirst(model.Db,
		adminTokenStruct.TableName(),
		&adminTokenStruct,
		model.QueryOptions{
			Conditions: map[string]interface{}{
				"refresh_token": requestData.RefreshToken,
			},
		})
	if !exists {
		controller.Fail(c, "token不存在")
		return
	}

	if err != nil {
		controller.Fail(c, "刷新失败"+err.Error())
		return
	}

	//刷新token
	accessToken, refreshToken, expires := adminTokenStruct.UpdateAccessToken(adminTokenStruct.AdminId)

	controller.Success(c, map[string]interface{}{
		"accessToken":  accessToken,
		"refreshToken": refreshToken,
		"expires":      expires,
	})

}
